package com.enation.app.javashop.consumer.job.execute.impl;

import com.enation.app.javashop.consumer.job.execute.EveryFiveMinExecute;
import com.enation.app.javashop.core.system.enums.WeChatPublicConstant;
import com.enation.app.javashop.core.system.enums.WeixinMiniproConstants;
import com.enation.app.javashop.core.system.service.WechatPublicManager;
import com.enation.app.javashop.framework.util.EnvironmentUtils;
import com.enation.app.javashop.framework.util.HttpUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * 非生产环境小程序和公众号accessToken定时刷新任务
 */
@Service
public class NonProdAccessTokenUpdateJob implements EveryFiveMinExecute{

    protected final Log logger = LogFactory.getLog(this.getClass());

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private WechatPublicManager wechatPublicManager;

    /**
     * 每5分钟执行
     */
    @Override
    public void everyFiveMin() {
        // 非生产环境刷新小程序token
        if(!EnvironmentUtils.isProd()){
            // 使用生产的小程序token
            String accessToken = HttpUtils.doGet("https://localhost/passport/mini-program/get-access-token");

            if (StringUtils.isNotBlank(accessToken)) {
                stringRedisTemplate.opsForValue().set(WeixinMiniproConstants.MINIPRO_ACCESS_TOKEN, accessToken);
            } else {
                logger.info("微信小程序accessToken刷新失败，未获取到正确值");
            }

            // 非生产环境刷新公众号token
            // 使用生产的公众号token
            String publicAccessToken = HttpUtils.doGet("https://localhost/wechat/public/get-access-token");
            if (StringUtils.isNotBlank(publicAccessToken)) {
                stringRedisTemplate.opsForValue().set(WeChatPublicConstant.WEIXIN_PUBLIC_TOKEN, publicAccessToken);
            } else {
                //wechatPublicManager.getTokenFromCache();//生产环境已经上线定时任务获取access_token功能时要关闭，防止测试影响生成
                logger.info("微信公众号accessToken刷新失败，未获取到正确值");
            }
        }
    }
}
